package com.xframe.xdal.core.es;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xframe.xdal.config.ElasticsearchConfigItem;
import com.xframe.xdal.core.DataBaseAccess;
import com.xframe.xdal.core.autofill.AutoProcRuntime;
import com.xframe.xdal.core.constant.DataSourceTypeEnums;
import com.xframe.xdal.core.constant.ErrorCode;
import com.xframe.xdal.core.constant.ErrorMsg;
import com.xframe.xdal.core.constant.RunOpportunity;
import com.xframe.xdal.core.exception.AutoProcRuntimeException;
import com.xframe.xdal.core.exception.DalFrameException;
import com.xframe.xdal.core.exception.SqlBuilderException;
import com.xframe.xdal.core.handler.BeanHandlerOptions;
import com.xframe.xdal.core.handler.es.EsBeanListHandler;
import com.xframe.xdal.core.handler.es.EsBeanObjectHandler;
import com.xframe.xdal.core.model.*;
import com.xframe.xdal.core.model.mapping.IColumnMapping;
import com.xframe.xdal.core.model.mapping.ITableInfo;
import com.xframe.xdal.core.model.mapping.TableInfoBuilder;
import com.xframe.xdal.core.model.page.IPagerModel;
import com.xframe.xdal.core.model.page.PagerModel;
import com.xframe.xdal.core.model.sqlbuilder.SqlKey;
import com.xframe.xdal.core.serialize.IJSONSer;
import com.xframe.xdal.core.serialize.JsonSerFactory;
import com.xframe.xdal.core.util.CollectionUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WrapperQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.BulkByScrollTask;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@Log4j2
public class ESCilent {

    private static Map<String, ESCilent> dbMap = new HashMap<>(8);


    private static String defName = null;

    public static void registerDataSource(ElasticsearchConfigItem configItem){

        if(!dbMap.containsKey(configItem.getName())){
            dbMap.put(configItem.getName(),new ESCilent(configItem));
        }
        if(defName == null){
            defName = configItem.getName();
        }
    }

    /**
     * 返回默认的ESCilent访问类
     *
     * @return ESCilent对象
     */
    public static ESCilent getInstance(){
        return dbMap.get(defName);
    }

    private ElasticsearchConfigItem configItem;
    private RestHighLevelClient client;

    private ESCilent(ElasticsearchConfigItem configItem){
        this.configItem = configItem;
        restHighLevelClient();
    }

    /**
     * 按照名称来返回数据库访问类
     * @param dataType 数据类型
     * @param model 模型
     *
     * @return DataAccessResult
     */
    public Integer addDocument(Class<?> dataType, IModel model) throws DalFrameException {
        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        DataAccessResult<Integer> result = addDocument(tableInfo,model,null);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }

    /**
     * 按照名称来返回数据库访问类
     * @param tableInfo 对象
     * @param model 模型
     * @param jsonSer 序列化对象
     * @return DataAccessResult
     */
    public DataAccessResult<Integer> addDocument(ITableInfo tableInfo, IModel model, IJSONSer jsonSer){
        DataAccessResult<Integer> result = new DataAccessResult<>(SqlKey.INSERT);
        try {
            if (tableInfo == null) {
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if (model == null) {
                throw new DalFrameException(ErrorCode.ARGS_ERROR, ErrorMsg.ARGS_ERROR_MSG);
            }
            if(jsonSer == null){
                jsonSer = JsonSerFactory.getDefaule();
            }
            AutoProcRuntime.getInstance().autoFill(model,tableInfo, RunOpportunity.C);
            IndexRequest indexRequest = new IndexRequest(tableInfo.getIndexName());
            indexRequest.id(model.getEsId()).source(jsonSer.toJson(model), XContentType.JSON);
            //indexRequest.id(model.getEsId()).source(JSON.toJSONString(model), XContentType.JSON);
            IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
            RestStatus status = response.status();
            if(status.equals(RestStatus.OK)||status.equals(RestStatus.CREATED)) {
                result.setDone(1, null);
            }else {
                result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR,result.toString()));
            }
        }catch (DalFrameException dalFrameException) {
            result.setError(dalFrameException.getCode(), dalFrameException);
        }
        catch (Exception e) {
            result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR, e.getMessage()));
        }
        return result;
    }


    /**
     * 批量添加数据到ES中
     * @param dataType 被查询的数据类型
     * @param collection 集合对象
     *
     * @return 收影响的行数
     */
    public <E> Integer batchAddDocument(Class<?> dataType, Collection<E> collection){
        return batchAddDocument(dataType,collection,null);
    }
    /**
     * 批量添加数据到ES中
     * @param dataType 被查询的数据类型
     * @param collection 集合对象
     * @param jsonSer 序列化对象
     * @return 收影响的行数
     */
    public <E> Integer batchAddDocument(Class<?> dataType, Collection<E> collection,IJSONSer jsonSer){
        DataAccessResult<Integer> result = batchAddDocumentOperate(dataType,collection,jsonSer);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }
    /**
     * 批量添加数据到ES中
     * @param dataType 被查询的数据类型
     * @param collection 集合对象
     * @param jsonSer 序列化对象
     * @return 收影响的行数
     */
    public <E> DataAccessResult<Integer> batchAddDocumentOperate(Class<?> dataType,Collection<E> collection,IJSONSer jsonSer){
        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        return batchAddDocumentOperate(tableInfo,collection,jsonSer);
    }
    /**
     * 批量添加数据到ES中
     * @param tableInfo 映射信息
     * @param collection 集合对象
     * @param jsonSer 序列化对象
     * @return 收影响的行数
     */
    public <E> DataAccessResult<Integer> batchAddDocumentOperate(ITableInfo tableInfo,Collection<E> collection,IJSONSer jsonSer){

        DataAccessResult<Integer> result = new DataAccessResult<>(SqlKey.MANY_INSERT);
        try {
            if (tableInfo == null) {
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if (CollectionUtil.isEmpty(collection)) {
                throw new DalFrameException(ErrorCode.ARGS_ERROR, ErrorMsg.ARGS_ERROR_MSG);
            }
            if(jsonSer == null){
                jsonSer = JsonSerFactory.getDefaule();
            }
            //自动填充处理
            AutoProcRuntime.getInstance().autoFill(collection,tableInfo, RunOpportunity.C);
            // 创建批量请求对象
            BulkRequest bulkRequest = new BulkRequest();
            for (Object  element  : collection) {
                if (element  instanceof IModel) {
                    IModel model = (IModel) element ;
                    AutoProcRuntime.getInstance().autoFill(model,tableInfo, RunOpportunity.C);
                    IndexRequest indexRequest = new IndexRequest(tableInfo.getIndexName());
                    indexRequest.id(model.getEsId()).source(jsonSer.toJson(model), XContentType.JSON);
                    bulkRequest.add(indexRequest);
                }
            }
            // 执行批量请求
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            RestStatus status = bulkResponse.status();
            if(status.equals(RestStatus.OK)||status.equals(RestStatus.CREATED)) {
                //result.setDone(1, null);
            }else {
                result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR,result.toString()));
            }
            // 处理每个操作的结果
            int okCount = 0;
            for (BulkItemResponse bulkItemResponse : bulkResponse) {

                if (bulkItemResponse.isFailed()) {
                    BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
                    // 处理失败情况
                } else {
                    // 处理成功情况
                    okCount++;
                }
            }
            result.setDone(okCount,null);
        }catch (Exception e) {
            result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR, e.getMessage()));
        }
        return result;
    }


    /**
     * 修改ES的数据
     * @param tableInfo 映射信息
     * @param model 集合对象
     *
     * @return 收影响的行数
     */
    public Integer updateDocument(ITableInfo tableInfo,IModel model){
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        DataAccessResult<Integer> result = updateDocument(tableInfo,model,null);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }

    /**
     * 修改ES的数据
     * @param dataType 映射信息
     * @param model 集合对象
     *
     * @return 收影响的行数
     */
    public Integer updateDocument(Class<?> dataType,IModel model){
        return updateDocument(dataType,model,null);
    }
    /**
     * 修改ES的数据
     * @param dataType 映射信息
     * @param model 集合对象
     * @param jsonSer 序列化对象
     * @return 收影响的行数
     */
    public Integer updateDocument(Class<?> dataType,IModel model,IJSONSer jsonSer) throws DalFrameException{
        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        DataAccessResult<Integer> result = updateDocument(tableInfo,model,jsonSer);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }

    /**
     * 修改ES的数据
     * @param tableInfo 映射信息
     * @param model 集合对象
     * @param jsonSer 序列化对象
     * @return 收影响的行数
     */
    public DataAccessResult<Integer> updateDocument(ITableInfo tableInfo, IModel model,IJSONSer jsonSer)  {
        DataAccessResult<Integer> result = new DataAccessResult<>(SqlKey.UPDATE);
        try {
            if (tableInfo == null) {
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if (model == null) {
                throw new DalFrameException(ErrorCode.ARGS_ERROR, ErrorMsg.ARGS_ERROR_MSG);
            }
            if(jsonSer == null){
                jsonSer = JsonSerFactory.getDefaule();
            }
            // 创建索引请求对象
            UpdateRequest updateRequest = new UpdateRequest(tableInfo.getIndexName(), model.getEsId());
            // 设置更新文档内容
            updateRequest.doc(jsonSer.toJson(model), XContentType.JSON);
            // 执行更新文档
            UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
            RestStatus status = response.status();
            if(status.equals(RestStatus.OK)) {
                result.setDone(1, null);
            }else {
                result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR,result.toString()));
            }
        }catch (DalFrameException dalFrameException) {
            result.setError(dalFrameException.getCode(), dalFrameException);
        }
        catch (Exception e) {
            result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR, e.getMessage()));
        }
        return result;
    }

    /**
     * @description:批量更新
     * @param:[dataType, collection]
     * @return:java.lang.Integer
     * @author: ChaiXinQiang
     * @createDate: 14:19 2023/6/8
     **/
    public <E> Integer batchUpdateDocument(Class<?> dataType, Collection<E> collection) throws DalFrameException{
        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        DataAccessResult<Integer> result = batchUpdateDocument(collection,tableInfo);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }

    public <E> DataAccessResult<Integer> batchUpdateDocument(Collection<E> collection,ITableInfo tableInfo ){
        DataAccessResult<Integer> result = new DataAccessResult<>(SqlKey.UPDATE_MANY);
        try {
            if (tableInfo == null) {
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if (CollectionUtil.isEmpty(collection)) {
                throw new DalFrameException(ErrorCode.ARGS_ERROR, ErrorMsg.ARGS_ERROR_MSG);
            }
            // 创建批量请求对象
            BulkRequest bulkRequest = new BulkRequest();
            for (Object  element  : collection) {
                if (element  instanceof IModel) {
                    IModel model = (IModel) element;
                    //自动填充处理
                    AutoProcRuntime.getInstance().autoFill(model,tableInfo, RunOpportunity.U);
                    UpdateRequest updateRequest = new UpdateRequest(tableInfo.getIndexName(), model.getEsId());
                    // 设置更新文档内容
                    updateRequest.doc(JSON.toJSONString(model), XContentType.JSON);
                    bulkRequest.add(updateRequest);
                }
            }
            // 执行批量请求
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            RestStatus status = bulkResponse.status();
            if(status.equals(RestStatus.OK)||status.equals(RestStatus.CREATED)) {
                result.setDone(1, null);
            }else {
                result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR,result.toString()));
            }
            // 处理每个操作的结果
            for (BulkItemResponse bulkItemResponse : bulkResponse) {
                if (bulkItemResponse.isFailed()) {
                    BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
                    // 处理失败情况
                } else {
                    // 处理成功情况
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.setError(ErrorCode.ES_QUERY_ERROR, new DalFrameException(ErrorCode.ES_QUERY_ERROR, e.getMessage()));
        }
        return result;
    }

    /**
     * 更新文档信息
     *
     * @param indexName 索引名称
     * @param object    文档数据
     * @param docId     数据id
     */
    public RestStatus updateDocument(String indexName, Object object, String docId) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(indexName, String.valueOf(docId));

        try {
            updateRequest.doc(JSON.toJSONString(object), XContentType.JSON);
            // 执行更新文档
            UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
            RestStatus status = response.status();
            log.info("更新文档信息响应状态-索引名称:{}, id:{}, 返回值:{}", indexName, docId, status);
            return status;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据文档ID删除一个对象
     *
     * @param dataType 数据类型
     * @param docId     数据id
     *
     * @return 收影响的行数
     */
    public Integer deleteDocument(Class<?> dataType,String docId) throws DalFrameException{
        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        DataAccessResult<Integer> result = deleteDocument(tableInfo,docId);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }
    /**
     * 根据文档ID删除一个对象
     *
     * @param tableInfo 映射信息
     * @param docId     数据id
     *
     * @return 收影响的行数
     */
    public DataAccessResult<Integer> deleteDocument(ITableInfo tableInfo, String docId)  {
        DataAccessResult<Integer> result = new DataAccessResult<>(SqlKey.DELETE);
        try {
            if (tableInfo == null) {
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if(docId == null){
                throw new DalFrameException(ErrorCode.ARGS_ERROR, ErrorMsg.ARGS_ERROR_MSG);
            }
            // 创建删除请求对象
            DeleteRequest deleteRequest = new DeleteRequest(tableInfo.getIndexName(), docId);
            // 执行删除文档
            DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
            RestStatus status = response.status();
            if(status.equals(RestStatus.OK)) {
                result.setDone(1, null);
            }else {
                result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR,result.toString()));
            }
        }
        catch (DalFrameException dalFrameException) {
            result.setError(dalFrameException.getCode(), dalFrameException);
        }
        catch (Exception e) {
            result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR, e.getMessage()));
        }
        return result;
    }



    public DataAccessResult<Long> deleteMany(ITableInfo tableInfo,FindOptions options){
        DataAccessResult<Long> result = new DataAccessResult<>(SqlKey.DELETE);
        try{
            if (tableInfo == null) {
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if(options == null){
                options = FindOptions.esFindAllOptions();
            }
            QueryBuilder boolQueryBuilder = options.getConditionValueCollection().builderBoolQueryBuilder();
            DeleteByQueryRequest request = new DeleteByQueryRequest(tableInfo.getIndexName());
            request.setQuery(boolQueryBuilder);
            BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);
            BulkByScrollTask.Status status = response.getStatus();
            log.info(response);
            // 处理每个操作的结果
//            int okCount = 0;
//            for (BulkItemResponse bulkItemResponse : response) {
//
//                if (bulkItemResponse.isFailed()) {
//                    BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
//                    // 处理失败情况
//                } else {
//                    // 处理成功情况
//                    okCount++;
//                }
//            }
            result.setDone(status.getDeleted(),null);
        }
        catch (DalFrameException dalFrameException) {
            result.setError(dalFrameException.getCode(), dalFrameException);
        }
        catch (Exception e) {
            result.setError(ErrorCode.ES_ADDDOCUMENT_ERROR, new DalFrameException(ErrorCode.ES_ADDDOCUMENT_ERROR, e.getMessage()));
        }
        return result;
    }

    /**
     * 删除文档信息
     *
     * @param indexName 索引名称
     * @param docId     数据id
     **/
    public RestStatus deleteDocument(String indexName, String docId){
        try {

            DeleteRequest deleteRequest = new DeleteRequest(indexName, docId);
            // 执行删除文档
            DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
            RestStatus status = response.status();
            log.info("删除文档-索引名称:{}, id:{}, 返回值:{}", indexName, docId, status);
            return status;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 批量导入
     *
     * @return
     * @throws IOException
     */
    public RestStatus batchImportGoodsData(String indexName, Map<String, Object> map) {
        BulkRequest bulkRequest = new BulkRequest();
        try {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                IndexRequest indexRequest = new IndexRequest(indexName);
                indexRequest.id(entry.getKey()).source(JSON.toJSONString(entry.getValue()), XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            RestStatus status = response.status();
            log.info("批量导入文档-索引名称:{}, 返回值:{}", indexName, status);
            return status;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 增加文档信息
     */
    public RestStatus addDocument(String indexName, String docId,
                                         String dataJson) {
        IndexRequest indexRequest = new IndexRequest(indexName);
        try {
            if (StrUtil.isNotEmpty(docId)) {
                indexRequest.id(docId).source(dataJson, XContentType.JSON);
            } else {
                indexRequest.source(dataJson, XContentType.JSON);
            }
            IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
            RestStatus status = response.status();
            log.info("创建文档-索引名称:{}, 状态:{}", indexName, status);
            return status;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 创建索引
     * @param indexName 索引名称
     * @return
     */
    public boolean indexCreate(String indexName){
        return indexCreate(indexName,null);
    }


    /**
     * 创建索引
     *
     * @param indexName
     * @return
     * @throws Exception
     */
    public boolean indexCreate(String indexName, String mapping){
        CreateIndexRequest indexRequest = new CreateIndexRequest(indexName);
        try {
            IndicesClient indicesClient = client.indices();
            if (StringUtils.isNotEmpty(mapping)) {
                indexRequest.mapping(mapping, XContentType.JSON);
            }
            CreateIndexResponse response = indicesClient.create(indexRequest, RequestOptions.DEFAULT);
            boolean acknowledged = response.isAcknowledged();
            return acknowledged;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 判断索引库是否存在
     * @param indexName 索引名称
     */
    public boolean indexExists(String indexName) {
        try {
            IndicesClient indicesClient = client.indices();
            GetIndexRequest request = new GetIndexRequest(indexName);
            // 判断索引库是否存在
            boolean result = indicesClient.exists(request, RequestOptions.DEFAULT);
            //log.info("判断是否存在索引-索引名称：{},返回值:{}", indexName, result);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 获取索引结构
     * GET goods/_mapping
     */
    public Map<String, Object> getMapping(String indexName) {
        try {
            IndicesClient indicesClient = client.indices();
            // 创建get请求
            GetIndexRequest request = new GetIndexRequest(indexName);
            // 发送get请求
            GetIndexResponse response = indicesClient.get(request, RequestOptions.DEFAULT);
            // 获取表结构
            Map<String, MappingMetaData> mappings = response.getMappings();
            Map<String, Object> sourceAsMap = mappings.get(indexName).getSourceAsMap();
            log.info("查询索引-索引名称：{}, 结果:{}", indexName, sourceAsMap);
            return sourceAsMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 删除索引
     */
    public boolean indexDelete(String indexName) {
        try {
            IndicesClient indicesClient = client.indices();
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
            // 发送delete请求
            AcknowledgedResponse response = indicesClient.delete(deleteIndexRequest, RequestOptions.DEFAULT);
            boolean acknowledged = response.isAcknowledged();
            log.info("删除索引-索引名称：{},返回值:{}", indexName, acknowledged);
            return acknowledged;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 根据DSL查询全量数据
     *
     * @param indexName 索引名称
     * @param body      查询dsl语句
     * @param
     * @return
     */
    public Map<String, Object> queryByDSL(String indexName, String body) {
        return queryEsResult(indexName, body, 0, true);
    }

    /**
     * 根据DSL查询数据
     *
     * @param indexName 索引名称
     * @param body      查询dsl语句
     * @param pageSize  每页多少条
     * @param flag      是否全量查询
     * @return
     */
    public Map<String, Object> queryByDSL(String indexName, String body, int pageSize, Boolean flag) {
        return queryEsResult(indexName, body, pageSize, flag);
    }
    /**
     * 根据DSL查询全量数据
     *
     * @param indexName 索引名称
     * @param pageSize  每一页条数
     * @param body      查询dsl语句
     * @return
     */
    public Map<String, Object> queryByDSL(String indexName, String body, int pageSize) {
        return queryEsResult(indexName, body, pageSize, true);
    }

    private static final int DEAL_TIME = 10000;
    private static final int PAGE_SIZE = 10000;

    private Map<String, Object> queryEsResult(String indexName, String body, int pageSize, Boolean flag) {
        Map<String, Object> map = new HashMap<>();
        try {
            JSONObject jsonObject = JSON.parseObject(body);
            Object obj = jsonObject.get("query");
            if (obj != null) {
                body = JSON.toJSONString(obj);
            } else {
                throw new DalFrameException(ErrorCode.ES_PARAM_NULL_ERROR, "查询参数异常");
            }
            WrapperQueryBuilder wrapperQueryBuilder = QueryBuilders.wrapperQuery(body);
            SearchRequest searchRequest = new SearchRequest(indexName);
            Scroll scroll = null;
            if (flag) {
                scroll = new Scroll(TimeValue.timeValueMillis(DEAL_TIME));
                searchRequest.scroll(scroll);
            }
            searchRequest.source(new SearchSourceBuilder().size(pageSize == 0 ? PAGE_SIZE : pageSize).query(wrapperQueryBuilder));
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            if (searchResponse != null && RestStatus.OK.equals(searchResponse.status()) && searchResponse.getHits().getTotalHits().value > 0) {
                SearchHits hits = searchResponse.getHits();
                if (!ObjectUtils.isEmpty(hits)) {
                    List<Object> dataList = new ArrayList();
                    SearchHit[] searchHits = hits.getHits();
                    if (flag) {
                        addResult(client, searchResponse, scroll, dataList);
                    } else {
                        dataList.add(searchHits);
                    }
                    map.put("data", dataList);
                    map.put("total", hits.getTotalHits().value);
                    return map;
                }
            }
        } catch (Exception e) {
            log.error("es 查询异常:{}", e.getMessage());
        }
        return null;
    }



    public <T> T findbyAk(Class<?> dataType, Object code){
        return findbyAk(dataType,TableInfoBuilder.BuildTableInfoByAnnotation(dataType),code);
    }

    public <T> T findbyAk(Class<?> dataType,ITableInfo tableInfo,Object code){
        return findbyAkOperate(dataType,tableInfo,code);
    }
    public <T> T findbyAkOperate(Class<?> dataType,
                          ITableInfo tableInfo,Object... codes){
        Collection<Object> vals = new ArrayList<>();
        for (Object code : codes){
            vals.add(code);
        }
        DataAccessResult<T> result = findbyAkOperate(dataType,tableInfo,vals);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }
    /**
     * 根据DSL查询全量数据
     *
     * @param dataType 数据类型
     * @param tableInfo
     * @param akValues  AK值
     * @return
     */
    public <T> DataAccessResult<T> findbyAkOperate(Class<?> dataType,
                          ITableInfo tableInfo,Collection<Object> akValues){
        DataAccessResult<T> result = new DataAccessResult<>(SqlKey.SEARCH_KEY);
        try {
            if(tableInfo == null){
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if(dataType == null){
                throw new DalFrameException(ErrorCode.ES_PARAM_NULL_ERROR, ErrorMsg.ES_PARAM_NULL_ERROR);
            }
            ConditionValueCollection conditionValueCollection = new ConditionValueCollection();
            List<IColumnMapping> columnMappingList = tableInfo.findUniqueKeyList();
            if (akValues.size() != columnMappingList.size()) {
                throw new DalFrameException(ErrorCode.ARGS_ERROR, "akValues值不匹配 args = akValues");
            }
            int index = 0;
            for (Object val : akValues) {
                conditionValueCollection.add(new ConditionValue(columnMappingList.get(index).getFieldName(), val));
                index++;
            }
            FindOptions options = FindOptions.esFindAllOptions();
            options.setConditionValueCollection(conditionValueCollection);
            DataAccessResult<T> listRes = query(tableInfo,dataType,options);
            if(!listRes.getSuccessFlag()){
                throw listRes.getException();
            }
            List collection = (List)listRes.getResult();
            if(collection != null && collection.size() > 0){
                result.setDone((T) collection.get(0),null);
            }else {
                result.setDone(null,null);
            }
        }catch (AutoProcRuntimeException autoProcRuntimeException){
            result.setError(ErrorCode.AUTOFILL_ERROR,autoProcRuntimeException, null);
        }catch (SqlBuilderException sqlException){
            result.setError(ErrorCode.SQL_BUILD_ERROR,sqlException, null);
        }catch (SQLException sqlException){
            result.setError(ErrorCode.SQL_ERROR,sqlException, null);
        }catch (DalFrameException e) {
            result.setError(e.getCode(),e, null);
        }catch (Exception exception) {
            result.setError(ErrorCode.DAL_UNKNOWN_ERROR,exception, null);
        }
        return result;
    }


    /**
     * 获取文档信息
     *
     * @param dataType  数据类型
     * @param id  主键
     *
     * @return DataAccessResult对象
     */
    public <T> T findOne(Class<?> dataType,Object id) throws DalFrameException {
        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        return findOne(tableInfo,dataType,id);
    }

    /**
     * 获取文档信息
     *
     * @param tableInfo 表结构
     * @param dataType  数据类型
     * @param id  主键
     *
     * @return DataAccessResult对象
     */
    public <T> T findOne(ITableInfo tableInfo,Class<?> dataType,Object id) throws DalFrameException {
        DataAccessResult<T> result = findOne(tableInfo,dataType,id,null);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }


    /**
     * 获取文档信息
     *
     * @param tableInfo 表结构
     * @param dataType  数据类型
     * @param id  主键
     * @param options 查询参数
     *
     * @return DataAccessResult对象
     */
    public <T> DataAccessResult<T> findOne(ITableInfo tableInfo,Class<?> dataType,Object id, FindOptions options){
        DataAccessResult<T> result = new DataAccessResult<>(SqlKey.PAGESEARCH);
        try {
            if(tableInfo == null){
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if(dataType == null){
                throw new DalFrameException(ErrorCode.ES_PARAM_NULL_ERROR, ErrorMsg.ES_PARAM_NULL_ERROR);
            }
            if(id == null){
                throw new DalFrameException(ErrorCode.ES_PARAM_NULL_ERROR, ErrorMsg.ES_PARAM_NULL_ERROR);
            }
            if(options == null){
                options = FindOptions.esFindAllOptions();
            }
            GetRequest getRequest = new GetRequest(tableInfo.getIndexName(), id.toString());
            GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
            BeanHandlerOptions beanHandlerOptions = new BeanHandlerOptions(tableInfo,null,
                    DataSourceTypeEnums.ES, options.getJsonSer(), AutoProcRuntime.getInstance());
            beanHandlerOptions.merge(options.getBeanHandlerOptions());
            T bean = (T) EsBeanObjectHandler.create(dataType,beanHandlerOptions).handle(response);
            result.setDone(bean,null);
        } catch (DalFrameException dalFrameException) {
            result.setError(dalFrameException.getCode(), dalFrameException);
        }
        catch (Exception e) {
            result.setError(ErrorCode.ES_QUERY_ERROR, new DalFrameException(ErrorCode.ES_QUERY_ERROR, e.getMessage()));
        }
        return result;
    }


    /**
     * 查询一个类型的所有数据
     *
     * @param dataType 数据类型
     * @return
     */
    public <T> T findAll(Class<?> dataType) throws DalFrameException{
        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        return findAll(tableInfo,dataType,FindOptions.esFindAllOptions());
    }

    public <T> T findAll(Class<?> dataType,FindOptions options) throws DalFrameException{
        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        return findAll(tableInfo,dataType,options);
    }

    public <T> T findAll(ITableInfo tableInfo,Class<?> dataType,FindOptions options) throws DalFrameException{
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        DataAccessResult<T> result = query(tableInfo,dataType,options);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }


    /**
     * 查询一个类型
     *
     * @param tableInfo 数据结构
     * @param dataType 数据类型
     * @param options 查询参数
     * @return
     */
    public <T> DataAccessResult<T> query(ITableInfo tableInfo,Class<?> dataType,FindOptions options){
        DataAccessResult<T> result = new DataAccessResult<>(SqlKey.PAGESEARCH);
        RestStatus restStatus = null;
        try {
            if(tableInfo == null){
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if(dataType == null){
                throw new DalFrameException(ErrorCode.ES_PARAM_NULL_ERROR, ErrorMsg.ES_PARAM_NULL_ERROR);
            }
            if(options == null){
                options = FindOptions.esFindAllOptions();
            }
            QueryBuilder boolQueryBuilder = options.getConditionValueCollection().builderBoolQueryBuilder();
            //log.info(boolQueryBuilder.toString());
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //searchSourceBuilder.size(options.getPageSize());
            searchSourceBuilder.size(PAGE_SIZE);
            SearchRequest searchRequest = new SearchRequest(tableInfo.getIndexName());
            searchRequest.source(searchSourceBuilder);
            if(options.getDbSortCollection() != null && options.getDbSortCollection().size() > 0){

                options.getDbSortCollection().SetSearchSourceBuilderSorts(searchSourceBuilder,tableInfo);
                //searchSourceBuilder.sort("billNo.keyword", SortOrder.DESC).sort("updateTime",SortOrder.DESC);
            }
            Scroll scroll = new Scroll(TimeValue.timeValueMillis(DEAL_TIME));
            searchRequest.scroll(scroll);
            searchSourceBuilder.query(boolQueryBuilder);

            // 执行查询，然后处理响应结果
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            restStatus = searchResponse.status();

            T fulllist = null;
            if (RestStatus.OK.equals(restStatus)) {
                SearchHits hits = searchResponse.getHits();
                BeanHandlerOptions beanHandlerOptions = new BeanHandlerOptions(tableInfo,null,
                        DataSourceTypeEnums.ES,options.getJsonSer(), AutoProcRuntime.getInstance());
                beanHandlerOptions.merge(options.getBeanHandlerOptions());

                EsBeanListHandler handler = EsBeanListHandler.create(dataType,beanHandlerOptions);


                fulllist = (T) handler.handle(hits);
                if(fulllist == null){
                    throw new DalFrameException(ErrorCode.ESBEANLISTHANDLER_ERROR,ErrorMsg.ESBEANLISTHANDLER_ERROR);
                }
                String scrollId = searchResponse.getScrollId();
                while (RestStatus.OK.equals(searchResponse.status()) && searchResponse.getHits().getHits().length > 0) {
                    SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
                    scrollRequest.scroll(scroll);
                    searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
                    if(searchResponse.getHits().getHits().length == 0){
                        break;
                    }
                    scrollId = searchResponse.getScrollId();

                    handler.handleMerge(searchResponse.getHits(),fulllist);

                }
                result.setDone(fulllist,null);
            }else {
                // 报错处理
                //log.info(searchResponse.status());
                result.setError(restStatus.getStatus(),new DalFrameException(restStatus.getStatus(),restStatus.name()));
            }

            //log.info("bool查询-索引名:{},返回值:{}", indexName, map);

        }catch (DalFrameException dalFrameException) {
            dalFrameException.printStackTrace();
            result.setError(dalFrameException.getCode(), dalFrameException);
        }
        catch (Exception e) {
            e.printStackTrace();
            result.setError(ErrorCode.ES_QUERY_ERROR, new DalFrameException(ErrorCode.ES_QUERY_ERROR, e.getMessage()));
        }
        return result;

    }





    /**
     * 分页查询一个类型
     *
     * @param dataType 数据类型
     *
     * @return IPagerModel<T> 分页返回结果集
     */
    public <T> IPagerModel<T> findAllByPage(Class<?> dataType) throws DalFrameException{
        return findAllByPage(dataType,null);
    }

    /**
     * 分页查询一个类型
     *
     * @param dataType 数据类型
     * @param options 查询参数
     * @return IPagerModel<T> 分页返回结果集
     */
    public <T> IPagerModel<T> findAllByPage(Class<?> dataType,FindOptions options) throws DalFrameException{

        ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(dataType);
        if(tableInfo == null){
            throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
        }
        DataAccessResult<IPagerModel<T>> result = querybyPage(tableInfo,dataType,options);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }

    /**
     * 分页查询一个类型
     *
     * @param tableInfo 数据结构
     * @param dataType 数据类型
     * @param options 查询参数
     * @return IPagerModel<T> 分页返回结果集
     */
    public <T> IPagerModel<T> findAllByPage(ITableInfo tableInfo,Class<?> dataType,FindOptions options) throws DalFrameException{
        DataAccessResult<IPagerModel<T>> result = querybyPage(tableInfo,dataType,options);
        if(!result.getSuccessFlag()){
            throw new DalFrameException(result.getCode(),result.getException().getMessage());
        }
        return result.getResult();
    }


    /**
     * 分页查询一个类型
     *
     * @param tableInfo 数据结构
     * @param dataType 数据类型
     * @param options 查询参数
     * @return DataAccessResult<IPagerModel<T>> 分页返回结果集
     */
    public <T> DataAccessResult<IPagerModel<T>> querybyPage(ITableInfo tableInfo,Class<?> dataType,FindOptions options){
        DataAccessResult<IPagerModel<T>> result = new DataAccessResult<>(SqlKey.PAGESEARCH);
        RestStatus restStatus = null;
        try {
            if(tableInfo == null){
                throw new DalFrameException(ErrorCode.NOT_FIND_TABLEINFO, ErrorMsg.TABLEINFO_NO_FIND_MSG);
            }
            if(dataType == null){
                throw new DalFrameException(ErrorCode.ES_PARAM_NULL_ERROR, ErrorMsg.ES_PARAM_NULL_ERROR);
            }
            if(options == null){
                options = FindOptions.esFindAllOptions();
            }
            IPagerModel pagerModel = new PagerModel(options.getPageIndex(), options.getPageSize());
            QueryBuilder boolQueryBuilder = options.getConditionValueCollection().builderBoolQueryBuilder();


            log.info(boolQueryBuilder.toString());

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            int from = (options.getPageIndex() - 1) * options.getPageSize();
            searchSourceBuilder.from(from);
            searchSourceBuilder.size(options.getPageSize());

            searchSourceBuilder.query(boolQueryBuilder);


            if(options.getDbSortCollection() != null && options.getDbSortCollection().size() > 0){

                options.getDbSortCollection().SetSearchSourceBuilderSorts(searchSourceBuilder,tableInfo);
                //searchSourceBuilder.sort("billNo.keyword", SortOrder.DESC).sort("updateTime",SortOrder.DESC);
            }

            log.info(searchSourceBuilder.toString());
            SearchRequest searchRequest = new SearchRequest(tableInfo.getIndexName());
            searchRequest.source(searchSourceBuilder);

            //log.info("bool查询-索引名:{},查询条件:{}", tableInfo.getIndexName(), searchRequest);
            // 执行查询，然后处理响应结果
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            restStatus = searchResponse.status();

            if (RestStatus.OK.equals(restStatus)) {
                SearchHits hits = searchResponse.getHits();
                BeanHandlerOptions beanHandlerOptions = new BeanHandlerOptions(tableInfo,null,
                        DataSourceTypeEnums.ES,options.getJsonSer(), AutoProcRuntime.getInstance());
                beanHandlerOptions.merge(options.getBeanHandlerOptions());
                T list = (T) EsBeanListHandler.create(dataType,beanHandlerOptions).handle(hits);
                pagerModel.setRecordCount(hits.getTotalHits().value);
                pagerModel.setDataList(list);
                result.setDone(pagerModel,null);
            }else {
                // 报错处理
                //log.info(searchResponse.status());
                result.setError(restStatus.getStatus(),new DalFrameException(restStatus.getStatus(),restStatus.name()));
            }
            //log.info("bool查询-索引名:{},返回值:{}", indexName, map);

        } catch (Exception e) {
            e.printStackTrace();
            result.setError(ErrorCode.ES_QUERY_ERROR, new DalFrameException(ErrorCode.ES_QUERY_ERROR, e.getMessage()));
        }
        return result;

    }

    /**
     * 组装返回值
     */
    private void addResult(RestHighLevelClient restHighLevelClient, SearchResponse searchResponse, Scroll scroll, List<Object> dataList) throws Exception {
        String scrollId = searchResponse.getScrollId();
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        while (RestStatus.OK.equals(searchResponse.status()) && searchHits.length > 0) {
            dataList.add(searchHits);
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
            scrollRequest.scroll(scroll);
            searchResponse = restHighLevelClient.scroll(scrollRequest, RequestOptions.DEFAULT);
            scrollId = searchResponse.getScrollId();
            searchHits = searchResponse.getHits().getHits();
        }
    }
    /**
     * 初始化RestHighLevelClient
     */
    private void restHighLevelClient() {

        // 拆分地址
        List<HttpHost> hostLists = new ArrayList<>();
        String[] hostList = configItem.getHosts().split(",");
        for (String addr : hostList) {
            String host = addr.split(":")[0];
            String port = addr.split(":")[1];
            hostLists.add(new HttpHost(host, Integer.parseInt(port), configItem.getScheme()));
        }
        // 转换成 HttpHost 数组
        HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});
        // 构建连接对象
        RestClientBuilder builder = RestClient.builder(httpHost);

        // 设置用户名、密码
//        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

        // 连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(configItem.getConnectTimeOut());
            requestConfigBuilder.setSocketTimeout(configItem.getSocketTimeOut());
            requestConfigBuilder.setConnectionRequestTimeout(configItem.getConnectionRequestTimeOut());
            return requestConfigBuilder;
        });
        // 连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(configItem.getMaxConnectNum());
            httpClientBuilder.setMaxConnPerRoute(configItem.getMaxConnectNumPerRoute());
            //  httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            return httpClientBuilder;
        });

        client = new RestHighLevelClient(builder);

    }
}
